package com.xingfudazi.app.service.impl;

import com.xingfudazi.app.domain.AppAccount;
import com.xingfudazi.app.domain.AppMember;
import com.xingfudazi.app.dto.WxJsCode2sessionResponse;
import com.xingfudazi.app.enums.MemberTypeEnum;
import com.xingfudazi.app.service.IAppAccountService;
import com.xingfudazi.app.service.IAppMemberService;
import com.xingfudazi.app.service.domain.WxRequestService;
import com.xingfudazi.app.service.AuthService;
import com.xingfudazi.common.exception.ExceptionEnum;
import com.xingfudazi.common.exception.ServiceException;
import com.xingfudazi.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 鉴权服务
 *
 * @author YuJiaMing
 * date 2023年11月03日 14:31
 */
@Slf4j
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private WxRequestService wxRequestService;

    @Autowired
    private IAppAccountService appAccountService;

    @Autowired
    private IAppMemberService appMemberService;

    @Override
    public AppAccount register(String code) {
        // 1、根据code手机号
        String phone = wxRequestService.getPhone(code);
        // String phone = "17852254286";
        log.info("根据code：{} 获取到的手机号为phone={}", code, phone);

        return tempRegister(phone);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AppAccount tempRegister(String phone) {
        // 2、查询是否有phone
        AppAccount appAccount = appAccountService.selectByUsername(phone);
        if (appAccount == null) {
            appAccount = new AppAccount();
            appAccount.initPhone(phone);
            appAccountService.insertAppAccount(appAccount);
            appAccount =  appAccountService.selectByUsername(phone);

            // 创造number
            this.appMemberService.init(appAccount);
        }
        return appAccount;
    }


    @Value("${xingfudazi.login}")
    private Boolean login;

    @Override
    public AppMember login(String code, String phone) {

        AppAccount appAccount = appAccountService.selectByUsername(phone);

        if (appAccount == null) {
            log.info("新增用户注册 phone= {}, 账户未授权", phone);
            throw ExceptionEnum.ACCOUNT_UNAUTHORIZED.unwrap();
        }

        if (login) {
            WxJsCode2sessionResponse wxJsCode2sessionResponse = wxRequestService.jsCode2session(code);
            String openId = wxJsCode2sessionResponse.getOpenId();
            String sessionKey = wxJsCode2sessionResponse.getSessionKey();
            // String openId = "test-open-id";
            // String sessionKey = "session-key"+System.currentTimeMillis();

            String originOpenId = appAccount.getWxOpenId();
            if (StringUtils.isNotEmpty(originOpenId) && !openId.equals(originOpenId)) {
                throw new ServiceException("非法手机号登录");
            }
            if (StringUtils.isEmpty(originOpenId)) {
                // 更新
                appAccount.setWxOpenId(openId);
                appAccountService.updateAppAccount(appAccount);
            }
        }


        // 获取用户身份信息
        return appMemberService.selectAppMember(appAccount.getId(), MemberTypeEnum.valueOf(appAccount.getMemberType()));
    }
}
